﻿using Common;
using DataBase.Models;
using Orleans;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Impl
{
    /// <summary>
    /// 路线集合
    /// </summary>
    internal class RouteImpl : Grain, IRoute
    {
        private    List<RouteItem>  list=new List<RouteItem>();
        private readonly ApplicationDBContext db;

        public RouteImpl(ApplicationDBContext adb)
        {
            db = adb;
        }


        public override async Task OnActivateAsync()
        {
            await base.OnActivateAsync();
            await 重置数据();
        }

        public Task<int> 获取两个地标之间的路由(string StartMarkerID, string EndMarkerID)
        {
            // StartMarkerID的位置必须小于EndMarkerID的位置
            int start, end;
            foreach (var sub in list)
            {
                start = -1;
                end = -1;
                for (int i = 0; i < sub.DotList.Count; i++)
                {
                    if (start == -1 && sub.DotList[i] == StartMarkerID)
                    {
                        start = i;
                    }
                    if (end == -1 && sub.DotList[i] == EndMarkerID)
                    {
                        end = i;
                    }
                    if (start > -1 && end > -1)
                    {
                        //跳出路线查找循环
                        break;
                    }
                }
                if (start > -1 && end > -1 && start < end)
                {
                    //找到了，返回结果（起始位必须小于结束位）
                    return Task.FromResult(sub.RouteNum);
                }
            }
            return Task.FromResult(0);
        }

        public Task 重置数据()
        {
            //从数据库中加载
            var 路线 = db.routeInfo.ToList();
            var tmp=new List<RouteItem>();

            路线.ForEach(item =>
            {
                var obj = new RouteItem()
                {
                    RouteNum = item.RouteID,
                    DotList = new List<string>()
                };
                var arr = item.Markers.Split(',');
                foreach(var m in arr)
                {
                    obj.DotList.Add(m); 
                }
                tmp.Add(obj);   
            });
            list = tmp;
            return Task.CompletedTask;
        }
    }

    #region 数据定义

    /// <summary>
    /// 每条路线的数据结构
    /// </summary>
    internal class RouteItem
    {
        /// <summary>
        /// 路线编号
        /// </summary>
        public int RouteNum { get; set; }



        /// <summary>
        /// 经过的地标点号（带顺序）
        /// </summary>
        public List<string> DotList { get; set; } = new List<string>();
    }


    #endregion
}
